from meiduo_admin.serializer.brand_serializer import *
from meiduo_admin.pages import MyPage
from rest_framework.generics import GenericAPIView
from goods.models import *
from rest_framework.response import Response


# GET goods/brands/
class BrandView(GenericAPIView):
    serializer_class = BrandSerializer
    queryset = Brand.objects.all()
    pagination_class = MyPage

    """展示所有商品"""
    def get(self, request):
        brands = self.get_queryset()
        page = self.paginate_queryset(brands)
        if page:
            page_serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(page_serializer.data)
        serializer = BrandSerializer(brands, many=True)
        return Response(serializer.data)

    def post(self, request):
        brand_add = self.request.data
        serializer = BrandSerializer(data=brand_add)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=201)


# GET goods/brands/undefined/
class BrandOnlyView(GenericAPIView):
    serializer_class = BrandSerializer
    queryset = Brand.objects.all()

    def get(self, request, pk):
        brand_obj = self.get_object()
        serializer = self.get_serializer(brand_obj)
        return Response(serializer.data)

    def put(self, request, pk):
        brand_obj = self.get_object()
        serializer = BrandSerializer(instance=brand_obj, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    def delete(self, request, pk):
        brand_obj = self.get_object()
        brand_obj.delete()
        return Response({})
